from .MyException import LosedArgumentException, NotSuppportedTypeException
import scrapy.item


class DB_operate_4_scrapy_class:
    def supported_type_juge(self, j_item):
        if not isinstance(j_item, scrapy.Item):
            raise NotSuppportedTypeException("not support for is type%s" % type(j_item))

    def insert_one_item_sql(self, one_item):
        self.supported_type_juge(one_item)
        suffix_sql = ''
        keys = one_item.keys()
        # values = one_item.values()

        values_palce_holder = ','.join(['%s'] * len(keys))
        fields_sql = ','.join(keys)
        suffix_sql = ' (%s) values(%s)' % (fields_sql, values_palce_holder)
        # print("insert one item sql : %s" % suffix_sql)
        return suffix_sql

    def insert_one_item_full_sql(self, one_item, pre_sql):
        return pre_sql + self.insert_one_item_sql(one_item)

    def insert_many_item_suffix_sql(self, items):
        self.supported_type_juge(items)
        if (len(items)) <= 0:
            return None
        return self.insert_one_item_sql()

    def update_one_by_single_older(self, new_item, table_name=None, old_item=None):
        self.supported_type_juge(new_item)
        self.supported_type_juge(old_item)
        if old_item is None:
            raise LosedArgumentException('缺少需要确定主键位置的参数')
        if table_name is None or len(table_name.strip()) == 0:
            raise LosedArgumentException('表名参数丢失 不能进行使用')

        sql = 'update tablename set  col_name = val,col_name = val2 where id = ? and io = ?'
        col_params = []
        col_params.extend(new_item.keys())
        col_val_params = []
        col_val_params.extend(new_item.values())

        indentified_params = []
        indentified_params.extend(old_item.keys())
        indentified_val_params = []
        indentified_val_params.extend(old_item.values())
        # 先渲染固定语句 在渲染?set col_n = val_n 先渲染col_n 再渲染val_n => ?
        sql = 'update %s set %s where %s' % (
        table_name, str(' =%s , '.join(col_params)) +' = %s ', str('= %s and '.join(indentified_params))) + ' = %s'
        vals_params = []
        vals_params.extend(col_val_params)
        vals_params.extend(indentified_val_params)
        #
        print("update one item %s  values : %s" % (sql,vals_params))
        return sql,tuple(vals_params)
